package org.tech4j.common.core.sign.extractor.parse;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.tech4j.common.spi.Join;
import org.tech4j.common.utils.JsonUtils;
import org.tech4j.common.core.request.param.ParameterDataFactory;

import java.util.Base64;
import java.util.Map;

/**
 * @program: tech4j-common
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/2 20:52
 **/
@Join
public class HeaderParseData implements ParseData {

    @Override
    public Triple<Map<String, Object>, String, String> parse(String paramType, String paramKey, HttpServletRequest request) {
        String data = ParameterDataFactory.buildData(paramType, paramKey, request);
        if (StringUtils.isBlank(data) || !data.contains(".")) {
            return null;
        }
        String[] tokenArray = StringUtils.split(data, '.');
        String parameters = tokenArray[0];
        String signature = tokenArray[1];

        Map<String, Object> headerMap = JsonUtils.toObjectMap(new String(Base64.getDecoder().decode(parameters)));
        return ImmutableTriple.of(headerMap, signature, parameters);
    }
}
